from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from web import models
from web.forms.issues import IssuesModelForm
from utils.pagination import Pagination


def  issues(request,project_id):
    if request.method == 'GET':
        # 根据URL做筛选，筛选条件（根据用户通过GET传过来的参数实现）
        # ?status=1&status=2&issues_type=1
        allow_filter_name = ['issues_type', 'status', 'priority', 'assign', 'attention']
        condition = {}
        for name in allow_filter_name:
            value_list = request.GET.getlist(name)  # [1,2]
            if not value_list:
                continue
            condition["{}__in".format(name)] = value_list
        """
        condition = {
            "status__in":[1,2],
            'issues_type':[1,]
        }
        """

        # 分页获取数据
        queryset = models.Issues.objects.filter(project_id=project_id).filter(**condition)
        page_object = Pagination(
            current_page=request.GET.get('page'),
            all_count=queryset.count(),
            base_url=request.path_info,
            query_params=request.GET,
            per_page=1
        )
        issues_object_list = queryset[page_object.start:page_object.end]
        #issues_object_list = models.Issues.objects.filter(project_id=project_id)
        print('issues_object_list----------------->',issues_object_list)
     
        form = IssuesModelForm(request)
        context = {
            'form': form,
            'issues_object_list': issues_object_list,
            'page_html': page_object.page_html()
        }
       
        return render(request,'issues.html',{'form':form,'context':context})

    print(request.POST)
    form = IssuesModelForm(request,data=request.POST)
    if form.is_valid():
        form.instance.project = request.saas.project
        form.instance.creator = request.saas.user
        # 添加问题
        form.save()
        return JsonResponse({'status':True})

    return JsonResponse({'status':False,'error':form.errors})